//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqRegister, reqLogin, reqLogout } from '@/api/user'
import { reqUserInfo, reqChatListFriends, reqUserFriends } from '@/api/messages'
//引入数据类型
import type {
    registerFormData,
    loginFormData,
    responseData,
    loginResponseData,
} from '@/api/user/type'
import type {
    friend,
    userInfoResponseData,
    userFriendsResponseData,
    chatListFriendsResponseData,
} from '@/api/messages/type'
//引入用户小仓库数据的ts类型
import type { UserState } from './types/type'
import type { RouteRecordRaw } from 'vue-router'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import {
    GET_FRIENDS,
    REMOVE_FRIENDS,
    SET_FRIENDS,
    GET_CHATLISTFRIENDS,
    SET_CHATLISTFRIENDS,
    REMOVE_CHATLISTFRIENDS,
} from '@/utils/friends'
import { REMOVE_CHAT } from '@/utils/chathistory'
//引入路由（常量路由）
import { constantRoute, anyRoute, navRoute } from '@/router/routes'
import router from '@/router'
//引入深拷贝方法
import cloneDeep from 'lodash/cloneDeep'

//用于生成当前用户需要展示的会话异步路由
const createChatRoute = (asyncRoute: RouteRecordRaw[], data: friend[]) => {
    data.forEach((item: friend) => {
        const friendRoute: RouteRecordRaw = {
            path: `/chat/friend/${item.userId}`,
            component: () => import('@/views/friend/index.vue'),
            meta: {
                userId: item.userId, //好友id
                conversationId: item.conversation_id, //会话id
                username: item.username, //好友用户名
                title: item.realname, //菜单标题，即好友名称
                avatar: item.avatar, //头像
                hidden: false, //代表路由标题在菜单中是否隐藏
            },
        }
        asyncRoute[0].children![0].children!.push(friendRoute)
    })
    return asyncRoute
}

//用于生成当前通讯录需要展示的好友异步路由
const createFriendshipRoute = (asyncRoute: RouteRecordRaw[], data: friend[]) => {
    data.forEach((item: friend) => {
        const friendshipRoute: RouteRecordRaw = {
            path: `/contacts/friendship/${item.userId}`,
            component: () => import('@/views/friendship/index.vue'),
            meta: {
                userId: item.userId, //好友id
                conversationId: item.conversation_id, //会话id
                username: item.username, //好友用户名
                title: item.realname, //菜单标题，即好友名称
                avatar: item.avatar, //头像
                hidden: false, //代表路由标题在菜单中是否隐藏
            },
        }
        asyncRoute[1].children![0].children!.push(friendshipRoute)
    })
    return asyncRoute
}

//创建用户小仓库
const useUserStore = defineStore('User', {
    //小仓库存储数据
    state: (): UserState => {
        return {
            userId: -1,
            menuRoutes: constantRoute, //仓库存储生成聊天好友菜单需要的数组（路由）
            navRoutes: navRoute, //最左侧导航栏的路由
            username: '请登录',
            avatar: 'https://gd-hbimg.huaban.com/689a639c005bddbad7bae709038b4fff36b8c9f2cdc8-PTyTst_fw236',
            realname: '',
            chatListFriends: GET_CHATLISTFRIENDS() as unknown as friend[],
            friends: GET_FRIENDS() as unknown as friend[],
            token: GET_TOKEN(), //获取用户唯一标识token
            changeAvatar: null, // 用户选择的即将更改的头像
        }
    },
    //异步、逻辑
    actions: {
        //用户注册的方法
        async userRegister(data: registerFormData) {
            const result: responseData = await reqRegister(data)
            //成功
            if (result.code == 200) {
                //保证当前async函数返回一个成功的promise
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        //用户登录的方法
        async userLogin(data: loginFormData) {
            const result: loginResponseData = await reqLogin(data)
            //成功
            if (result.code == 200) {
                //在pinia仓库储存一下token
                this.token = result.data.token
                //本地存储持久化存储一份
                SET_TOKEN(result.data.token)
                //保证当前async函数返回一个成功的promise
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        //获取用户信息的方法
        async userInfo() {
            const userInfo: userInfoResponseData = await reqUserInfo()
            const userFriends: userFriendsResponseData = await reqUserFriends()
            const chatListFriends: chatListFriendsResponseData = await reqChatListFriends()
            //如果获取用户信息成功，储存用户信息
            if (userInfo.code == 200) {
                this.userId = userInfo.data.userId
                this.username = userInfo.data.username
                this.avatar = userInfo.data.avatar
                this.realname = userInfo.data.realname
                this.chatListFriends = chatListFriends.data
                this.friends = userFriends.data
                //本地存储持久化存储一份聊天好友信息
                SET_CHATLISTFRIENDS(chatListFriends.data)
                //本地存储持久化存储一份好友信息
                SET_FRIENDS(userFriends.data)
                //计算当前用户会话需要展示的异步路由
                const chatAsyncRoute = createChatRoute(cloneDeep(navRoute), chatListFriends.data)
                //计算用户好友通讯录需要展示的异步路由
                const friendshipAsyncRoute = createFriendshipRoute(chatAsyncRoute, userFriends.data)
                this.menuRoutes = [...friendshipAsyncRoute, ...constantRoute, ...anyRoute]
                //目前路由器管理的只有常量路由，用户异步路由计算完毕后需动态追加
                ;[...friendshipAsyncRoute, ...anyRoute].forEach((route: any) => {
                    router.addRoute(route)
                })
                return 'ok'
            } else {
                const error = userInfo.message + userFriends.message
                return Promise.reject(new Error(error))
            }
        },
        //退出登录的方法
        async userLogout() {
            const result: any = await reqLogout()
            if (result.code == 200) {
                this.userId = -1
                this.token = ''
                this.username = '请登录'
                this.avatar =
                    'https://gd-hbimg.huaban.com/689a639c005bddbad7bae709038b4fff36b8c9f2cdc8-PTyTst_fw236'
                this.menuRoutes = constantRoute
                this.realname = '用户未登录'
                this.chatListFriends = []
                this.friends = []
                REMOVE_TOKEN()
                REMOVE_CHATLISTFRIENDS()
                REMOVE_FRIENDS()
                REMOVE_CHAT()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
    },
    getters: {},
})

//对外暴露获取小仓库的方法
export default useUserStore
